<template>

    <div>
        <p>
            <button @click="list" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-refresh green"></i>
                刷新
            </button>
            &nbsp;
            <button @click="add" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-edit red"></i>
                新增
            </button>
        </p>
        <pagination ref="pagination" v-bind:list="list"/>

        <div class="row">
            <div v-for="course in courses" class="col-md-3">
                <div class="thumbnail search-thumbnail">
                    <img v-show="!course.image" class="media-object" src="/static/image/demo-course.jpg"/>
                    <img v-show="course.image" class="media-object" v-bind:src="course.image"/>
                    <div class="caption">
                        <div class="clearfix">
              <span class="pull-right label label-primary info-label">
                  {{$filters.optionKV(course_level,course.level)}}
              </span>
                            <span class="pull-right label label-primary info-label">
                {{$filters.optionKV(course_charge,course.charge)}}
              </span>
                            <span class="pull-right label label-primary info-label">
               {{$filters.optionKV(course_status,course.status)}}
              </span>
                        </div>

                        <h3  class="search-title">
                            <a href="#" class="blue">{{course.name}}</a>
                        </h3>


                        <div v-for="teacher in teachers.filter(t=>{return t.id===course.teacherId})" class="profile-activity clearfix">
                            <div>
                                <img v-show="!teacher.image" class="pull-left"
                                     src="/assets/images/avatars/avatar5.png">
                                <img v-show="teacher.image" class="pull-left" v-bind:src="teacher.image">
                                <a class="user" href="#"> {{teacher.name || '暂无名称'}} </a>
                                <br>
                                {{teacher.position || '暂无职位'}}
                            </div>
                        </div>

                        <p>
                            <span class="blue bolder bigger-150">{{course.price}}&nbsp;<i class="fa fa-rmb"></i></span>&nbsp;
                        </p>
                        <p>{{course.summary}}</p>
                        <p><span class="badge badge-info">ID: {{course.id}}</span></p>
                        <p>
                            <span class="badge badge-info">排序：{{course.sort}}</span>
                            <span class="badge badge-info">时长: {{$filters.formatSecond(course.time)}}</span>
                        </p>
                        <p>
                            <button v-on:click="toChapter(course)" class="btn btn-white btn-xs btn-info btn-round">
                                大章
                            </button>&nbsp;
                                                        <button @click="toContent(course)"  class="btn btn-white btn-xs btn-info btn-round">
                                                            内容
                                                        </button>&nbsp;
                                                        <button v-on:click="openSortModal(course)" class="btn btn-white btn-xs btn-info btn-round">
                                                            排序
                                                        </button>&nbsp;
                            <button v-on:click="edit(course)" class="btn btn-white btn-xs btn-info btn-round">
                                编辑
                            </button>&nbsp;
                            <button v-on:click="handledelete(course.id)"
                                    class="btn btn-white btn-xs btn-warning btn-round">
                                删除
                            </button>
                        </p>
                    </div>
                </div>
            </div>
        </div>


        <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">表单</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">分类:</label>
                                <div class="col-sm-10">
                                    <ul id="tree" class="ztree"></ul>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">封面:</label>
                                <div class="col-sm-10">
                                    <big-file v-bind:text="'上传封面'" v-bind:input-id="'image-upload'"
                                          v-bind:after-upload="afterUpload"
                                          v-bind:suffixs="['jpg','jpeg','png']"
                                          v-bind:use="FILE_USE.COURSE.key"></big-file>
                                    <div v-show="courseinfo.image" class="row">
                                        <div class="col-md-6">
                                            <img v-bind:src="courseinfo.image" class="img-responsive"/>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">名称:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.name" class="form-control" placeholder="名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">讲师:</label>
                                <div class="col-sm-10">
                                    <select v-model="courseinfo.teacherId" class="form-control">
                                        <option v-for="o in teachers" v-bind:value="o.id">{{o.name}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">概述:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.summary" class="form-control"
                                           placeholder="概述">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">时长:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.time" class="form-control" placeholder="时长">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">价格:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.price" class="form-control" placeholder="价格">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">级别:</label>
                                <div class="col-sm-10">
                                    <select v-model="courseinfo.level" class="form-control">
                                        <option v-for="o in course_level" v-bind:value="o.key">{{o.value}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">收费:</label>
                                <div class="col-sm-10">
                                    <select v-model="courseinfo.charge" class="form-control">
                                        <option v-for="o in course_charge" v-bind:value="o.key">{{o.value}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">状态:</label>
                                <div class="col-sm-10">
                                    <select v-model="courseinfo.status" class="form-control">
                                        <option v-for="o in course_status" v-bind:value="o.key">{{o.value}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">报名数:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.enroll" class="form-control"
                                           placeholder="报名数">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">顺序:</label>
                                <div class="col-sm-10">
                                    <input type="text" v-model="courseinfo.sort" class="form-control" placeholder="顺序" disabled>
                                </div>
                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" @click="save" class="btn btn-primary">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->


        <div class="modal fade" id="course-sort-modal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">排序</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">当前排序</label>
                                <div class="col-lg-6">
                                    <input class="form-control" v-model="sort.oldSort" name="oldSort" disabled />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">新排序</label>
                                <div class="col-lg-6">
                                    <input class="form-control" v-model="sort.newSort" name="newSort">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" @click="updateSort" class="btn btn-primary">保存排序</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->



    </div><!-- /.row -->


</template>


<style scoped>
    .caption h3 {
        font-size: 20px;
    }
    /*自适应，若屏幕尺寸小于1199px 字体大小改变*/
    @media (max-width: 1199px) {
        .caption h3 {
            font-size: 16px;
        }
    }

</style>

<script scope>
    import axios from 'axios';
    import {defineComponent, onMounted, ref,computed} from 'vue';
    import Pagination from '@/components/pagination.vue';
    import BigFile from '@/components/big-file.vue';
    import OssBigFile from '@/components/oss-big-file.vue';
    import router from "../../router";

    export default defineComponent({
        name: 'course',
        components:{
            BigFile,OssBigFile,
            Pagination
        },
        setup() {
            const courses = ref();
            const pagination = ref({});
            const courseinfo=ref({});
            const categorys=ref();

            let tree={};
            let sort=ref({
               id: "",
               oldSort:0,
               newSort:0
            });
            let teachers=ref([]);
            const course_level=COURSE_LEVEL;
            const course_charge=COURSE_CHARGE;
            const course_status=COURSE_STATUS;

            const list = () => {
                Loading.show();
                axios.get("/business/admin/course/list", {
                    params: {
                        page: pagination.value.page,
                        size: pagination.value.size,
                    }
                }).then((response) => {
                    Loading.hide();
                    const data=response.data;
                    if (data.success){
                        courses.value = data.content.list;
                        pagination.value.render(pagination.value.page,data.content.total);
                    }else {
                        Toast.warning(data.message);
                    }

                })
            };

            const add=()=>{
                //初始化
                courseinfo.value={
                    sort: pagination.value.total+1
                };
                //树全部不选择
                tree.checkAllNodes(false);
                $('#myModal').modal();
            };

            /**
             * 编辑
             */
            const edit = (course) => {
                //查找当前选择课程下的分类
                listCategory(course.id);
                $('#myModal').modal();
                courseinfo.value = Tool.copy(course);

            };

            /**
             * 删除
             */
            const handledelete = (id) => {
                Confirm.show("删除课程后不可恢复，确认删除？", function () {
                    Loading.show();
                    axios.delete("/business/admin/course/delete/" + id).then((response) => {
                        Loading.hide();
                        const data = response.data;
                        if (data.success) {
                            list();
                            Toast.success("删除成功!");
                        }else{
                            Toast.warning(data.message);
                        }
                    })
                });
            };

            const save=()=>{
                // 保存校验
                if (1 != 1
                    || !Validator.require(courseinfo.value.name, "名称")
                    || !Validator.length(courseinfo.value.name, "名称", 1, 50)
                    || !Validator.length(courseinfo.value.summary, "概述", 1, 2000)
                    || !Validator.length(courseinfo.value.image, "封面", 1, 100)
                ) {
                    return;
                }
                let categorys=tree.getCheckedNodes();
                if(Tool.isEmpty(categorys)){
                    Toast.warning("请选择分类!");
                    return;
                }
                courseinfo.value.categorys=categorys;


                Loading.show();
                axios.post("/business/admin/course/save",courseinfo.value).then((response) => {
                    const data=response.data;
                    Loading.hide();
                    if (data.success){
                        $('#myModal').modal('hide');
                        // console.log(data);
                        list();
                        Toast.success("保存成功！");
                    }else{
                        Toast.warning(data.message);
                    }

                })
            };

            /**
             * 点击[大章]
             */
            const toChapter = (course) => {
                //存值
                SessionStorage.set(SESSION_KEY_COURSE,course);
                //界面跳转
                router.push("/business/chapter");
            };


            /**
             * 点击[内容]
             */
            const toContent = (course) => {
                //存值
                SessionStorage.set(SESSION_KEY_COURSE,course);
                //界面跳转
                router.push("/business/content");
            };

            /*
            * 查询所有分类
            *
            * */
            const allCategory = () => {
                Loading.show();
                axios.get("/business/admin/category/all").then((response) => {
                    Loading.hide();
                    const data=response.data;
                    if (data.success){
                        categorys.value = data.content;
                        initTree();
                    }else {
                        Loading.hide();
                        Toast.warning(data.message);
                    }

                })
            };


            /*
            * 查询课程下所有分类
            *
            * */
            const listCategory = (courseId) => {
                axios.get("/business/admin/course/list-category/"+courseId).then((response) => {
                    const data=response.data;
                    if (data.success){
                        categorys.value = data.content;

                        tree.checkAllNodes(false);
                        for(let i=0;i<categorys.value.length;i++){
                            let node =tree.getNodeByParam("id",categorys.value[i].categoryId);
                            tree.checkNode(node,true);
                        }
                    }else {
                        Toast.warning(data.message);
                    }

                })
            };


            /*
            * 初始化树
            * */
            const initTree=()=>{
                let setting={
                    check:{
                        enable: true
                },
                    data:{
                        simpleData:{
                            idKey: "id",
                            pIdKey: "parent",
                            rootPId: "0",
                            enable: true
                        }
                    }
                };
                 let zNodes=categorys.value;
                tree= $.fn.zTree.init($("#tree"),setting,zNodes);
                //初始化的时候默认关闭所有节点
                tree.expandAll(false);

            }


            /*
            * 打开排序模态框
            * */
            const openSortModal=(course)=>{
                sort.value={
                    id: course.id,
                    oldSort: course.sort,
                    newSort: course.sort

                };
                $("#course-sort-modal").modal("show");
            }

            /**
             * 更新排序
             *
             */
            const updateSort=()=>{
                if(sort.value.newSort === sort.value.oldSort){
                    Toast.warning("排序没有变化");
                    return;
                }
                Loading.show();
                axios.post("/business/admin/course/sort",sort.value).then((response)=>{
                    const data=response.data;
                    if(data.success){
                        Toast.success("更新排序成功!");
                        $('#course-sort-modal').modal('hide');
                        list();
                    }else{
                        Toast.error("更新排序失败!");
                    }
                })
            }

            /*
          * 查询所有讲师
          *
          * */
            const allTeacher = () => {
                Loading.show();
                axios.get("/business/admin/teacher/all").then((response) => {
                    Loading.hide();
                    const data=response.data;
                    if (data.success){
                        teachers.value = data.content;
                    }else {
                        Toast.warning(data.message);
                    }

                })
            };

            /*
            * 上传课程封面
            * */
            const afterUpload=(data)=>{
                let image=data.content.path;
                courseinfo.value.image=image;
            }


            onMounted(() => {
                list();
                allCategory();
                allTeacher();
            });

            return {
                list,
                add,
                edit,
                handledelete,
                pagination,
                courseinfo,
                save,
                toChapter,
                courses,
                course_level,
                course_charge,
                course_status,
                initTree,
                allCategory,
                categorys,
                tree,
                openSortModal,
                updateSort,
                sort,
                teachers,
                afterUpload,
                toContent,
                FILE_USE
            }


        }
    });
</script>